package com.pub.paypal.controller;

import com.paypal.base.rest.PayPalRESTException;
import com.pub.paypal.common.util.RequestToMapUtil;
import com.pub.paypal.common.vo.PaypalVo;
import com.pub.paypal.service.CallbackService;
import com.pub.paypal.service.PaypalService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * paypal回调处理
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/paypal")
public class CallbackController {

    private CallbackService callbackService;

    private PaypalService paypalService;

    /**
     * ipn异步回调
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/call/back")
    public String callback(HttpServletRequest request, HttpServletResponse response) {
        return callbackService.callback(RequestToMapUtil.getParameterMap(request));
    }

    /**
     * 执行支付：这里对应创建paypal订单时传的return_url，支付后paypal会调用该地址进行扣款操作
     * @param token
     * @param PayerID
     * @return 重定向paypal地址
     * @throws PayPalRESTException
     */
    @GetMapping(value ="/return_url" )
    public String successPay(@RequestParam("token") String token, @RequestParam("PayerID") String PayerID){
        try {
            PaypalVo result = paypalService.successPay(token,PayerID);
            if("SUCCESS".equals(result.getIsPaySuccess())){
                return "redirect:/paypal/list";  //返回订单页面
            }
        } catch (PayPalRESTException e) {
            e.printStackTrace();
        }
        return "redirect:/";
    }

    /**
     * 订单取消
     * @param token
     * @throws PayPalRESTException
     */
    @GetMapping(value ="/cancel_url" )
    public void successPay(@RequestParam("token") String token){
        System.out.println(token);
    }
}
